package com.example.ivideo_2211a.activity

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter

import com.google.android.gms.ads.*
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdOptions
import com.example.ivideo_2211a.databinding.ActivitySplashBinding


/**
 * 启动页Activity
 * 负责展示启动页、加载并显示广告、倒计时跳过功能
 * 使用ARouter进行页面路由管理
 */
@Route(path = "/app/SplashActivity")
class SplashActivity : AppCompatActivity() {
    // 标记是否点击了跳过按钮
    private var isSkipClicked = false
    // 跳过按钮倒计时时间(毫秒)
    private val skipDuration = 5000L // 5秒

    // 视图绑定对象
    private lateinit var binding: ActivitySplashBinding
    // 插屏广告对象
    private var interstitialAd: InterstitialAd? = null
    // 原生广告对象
    private var nativeAd: NativeAd? = null

    companion object {
        private const val TAG = "SplashActivity"
        // 测试广告单元ID - 正式发布时需要替换为真实的广告单元ID
        private const val INTERSTITIAL_AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712"
        private const val NATIVE_AD_UNIT_ID = "ca-app-pub-3940256099942544/2247696110"
    }

    /**
     * Activity创建时调用
     * @param savedInstanceState 保存的实例状态
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化视图绑定
        binding = ActivitySplashBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 初始化广告
        initializeAds()

        // 启动自定义圆形倒计时动画，设置倒计时时间和间隔
        binding.skipCircle.start(skipDuration, 5)
        // 设置跳过按钮点击监听器
        binding.skipCircle.setOnClickListener {
            isSkipClicked = true
            navigateToMainActivity()
        }
        // 设置倒计时结束回调，自动跳转或展示插屏广告
        binding.skipCircle.onSkip = {
            if (!isSkipClicked) {
                showInterstitialAdOrNavigate()
            }
        }
    }


    /**
     * 初始化所有广告类型
     */
    private fun initializeAds() {
        // 加载Banner广告
        loadBannerAd()

        // 加载插屏广告
        loadInterstitialAd()

        // 加载原生广告
        loadNativeAd()
    }

    /**
     * 加载Banner广告
     */
    private fun loadBannerAd() {
        val adRequest = AdRequest.Builder().build()
        binding.adView.loadAd(adRequest)

        binding.adView.adListener = object : AdListener() {
            override fun onAdClicked() {
                Log.d(TAG, "Banner广告被点击")
            }

            override fun onAdClosed() {
                Log.d(TAG, "Banner广告关闭")
            }

            override fun onAdFailedToLoad(adError: LoadAdError) {
                Log.e(TAG, "Banner广告加载失败: ${adError.message}")
                binding.adView.visibility = View.VISIBLE
            }

            override fun onAdImpression() {
                Log.d(TAG, "Banner广告展示")
            }

            override fun onAdLoaded() {
                Log.d(TAG, "Banner广告加载成功")
                binding.adView.visibility = View.VISIBLE
            }

            override fun onAdOpened() {
                Log.d(TAG, "Banner广告打开")
            }
        }
    }

    /**
     * 加载插屏广告
     */
    private fun loadInterstitialAd() {
        val adRequest = AdRequest.Builder().build()

        InterstitialAd.load(this, INTERSTITIAL_AD_UNIT_ID, adRequest,
            object : InterstitialAdLoadCallback() {
                override fun onAdFailedToLoad(adError: LoadAdError) {
                    Log.e(TAG, "插屏广告加载失败: ${adError.message}")
                    interstitialAd = null
                }

                override fun onAdLoaded(ad: InterstitialAd) {
                    Log.d(TAG, "插屏广告加载成功")
                    interstitialAd = ad

                    // 设置插屏广告回调
                    interstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
                        override fun onAdClicked() {
                            Log.d(TAG, "插屏广告被点击")
                        }

                        override fun onAdDismissedFullScreenContent() {
                            Log.d(TAG, "插屏广告关闭")
                            interstitialAd = null
                            navigateToMainActivity()
                        }

                        override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                            Log.e(TAG, "插屏广告显示失败: ${adError.message}")
                            interstitialAd = null
                            navigateToMainActivity()
                        }

                        override fun onAdImpression() {
                            Log.d(TAG, "插屏广告展示")
                        }

                        override fun onAdShowedFullScreenContent() {
                            Log.d(TAG, "插屏广告显示")
                        }
                    }
                }
            })
    }

    /**
     * 加载原生广告
     */
    private fun loadNativeAd() {
        val builder = AdLoader.Builder(this, NATIVE_AD_UNIT_ID)

        builder.forNativeAd { ad: NativeAd ->
            Log.d(TAG, "原生广告加载成功")
            nativeAd?.destroy()
            nativeAd = ad
        }

        val videoOptions = VideoOptions.Builder()
            .setStartMuted(true)
            .build()

        val adOptions = NativeAdOptions.Builder()
            .setVideoOptions(videoOptions)
            .build()

        builder.withNativeAdOptions(adOptions)

        val adLoader = builder.withAdListener(object : AdListener() {
            override fun onAdFailedToLoad(adError: LoadAdError) {
                Log.e(TAG, "原生广告加载失败: ${adError.message}")
            }
        }).build()

        adLoader.loadAd(AdRequest.Builder().build())
    }

    // 旧的 startCountDown 逻辑已移除，全部由 skipCircle 控件动画和回调控制

    // 立即显示插屏广告时无需再隐藏 tvSkip
    /**
     * 立即显示插屏广告
     */
    private fun showInterstitialAdImmediately() {
        if (interstitialAd != null) {
            Log.d(TAG, "立即显示插屏广告")
            interstitialAd?.show(this)
        }
    }

    /**
     * 显示插屏广告或直接跳转到主页面
     */
    private fun showInterstitialAdOrNavigate() {
        if (interstitialAd != null) {
            Log.d(TAG, "显示插屏广告")
            interstitialAd?.show(this)
        } else {
            Log.d(TAG, "插屏广告未准备好，直接跳转")
            navigateToMainActivity()
        }
    }

    /**
     * 跳转到主页面
     */
    private fun navigateToMainActivity() {
        ARouter.getInstance().build("/app/MainActivity").navigation()

    }

    /**
     * Activity销毁时调用，释放广告资源
     */
    override fun onDestroy() {
        super.onDestroy()
        nativeAd?.destroy()
        binding.adView.destroy()
    }

    /**
     * Activity暂停时调用，暂停广告
     */
    override fun onPause() {
        super.onPause()
        binding.adView.pause()
    }

    /**
     * Activity恢复时调用，恢复广告
     */
    override fun onResume() {
        super.onResume()
        binding.adView.resume()
    }
}
